/*  File Name	: SockConnector.cpp
 *  Author		: Pang Jiacai
 *	 E-mail		: 823960168@qq.com
 *  Created on	: 2012-6-25
 *  Description:
 */

#include "SockConnector.h"
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
SockConnector::SockConnector()
{

}

SockConnector::~SockConnector()
{

}

/*
 * block connect
 */
int SockConnector::connect(SockStream *peer,std::string ip,int port,TimeValue &timeout,
		int pro_family,int type,int protocol,bool reuseaddr)
{
	if(peer->get_handle()==-1)
	{
		if(peer->open(pro_family,type,protocol,reuseaddr)!=0)
		{
			return -1;
		}
	}

//	if(timeout!=TimeValue::zero && peer->enable(O_NONBLOCK)!=0)
//	{
//		return -1;
//	}

	struct sockaddr_in remote_addr;
	bzero(&remote_addr, sizeof(remote_addr));
	remote_addr.sin_addr.s_addr = inet_addr(ip.c_str());
	remote_addr.sin_port = htons(port);
	remote_addr.sin_family = pro_family;

	int result =::connect(peer->get_handle(),(sockaddr*)&remote_addr,sizeof(sockaddr));

	if(result==-1)
	{
		peer->close();
	}
	return result;
}
